package com.example.myproject.web;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class CookieUtil {
	protected final static transient Log log = LogFactory.getLog(CookieUtil.class);
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}

	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位 -1 代表浏览器的生命周期，0 代表
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge,String domain){
		Cookie cookie = new Cookie(name,value);
		cookie.setPath("/");
		cookie.setMaxAge(maxAge);
		cookie.setDomain(domain);
		response.addCookie(cookie);
	}

	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 */
	public static void cleanCookie(HttpServletResponse response,String name,String domain){
		Cookie cookie = new Cookie(name,null);
		cookie.setPath("/");
		cookie.setMaxAge(0);
		cookie.setDomain(domain);
		response.addCookie(cookie);
	}
	public static void cleanCookie(HttpServletRequest request,String name){
		 Map<String,Cookie> cookieMap = ReadCookieMap(request);
		    if(cookieMap.containsKey(name)){
		        Cookie cookie = (Cookie)cookieMap.get(name);
		        cookie.setMaxAge(0);
		    }   
	}
	
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return

	 */

	public static Cookie getCookieByName(HttpServletRequest request,String name){
	    Map<String,Cookie> cookieMap = ReadCookieMap(request);
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    return cookieMap;
	}

	/**
	 * 获取cookie值
	 *
	 * @param name
	 * @param request
	 * @return
	 */
	public static String getValue(String name, HttpServletRequest request) {
		Cookie ck = getCookieByName(request, name);
		String value = null;
		if(ck != null){
			try{
				value =  URLDecoder.decode(ck.getValue(), "UTF-8");
			}catch (UnsupportedEncodingException e){
				e.printStackTrace();
			}
		}
		return value;
	}

	/**
	 * 设置Cookie 来做分布式session 验证 设置过期时间为下天的6点钟。明天的6天之后需要重新登录
	 *
	 * @param name
	 * @param value
	 * @param response
	 */
	public static void setCookieForSession(String name, String value, HttpServletResponse response, boolean httpOnly, boolean secure) {
		long start = System.currentTimeMillis();
		Calendar end2 = Calendar.getInstance();
		end2.set(Calendar.HOUR_OF_DAY,6);
		end2.set(Calendar.MINUTE,0);
		//expiry 单位是秒
		int expiry = (int) (end2.getTime().getTime()- start)/1000;
		log.info("setCookieForSession expiry time:"+end2.getTime());
		setCookie(name, value, -1, response, httpOnly, secure);//-1代表session窗口过期

	}

	/**
	 * 设置cookie
	 *
	 * @param name
	 * @param value
	 * @param expiry 过期时间
	 * @param response
	 */
	public static void setCookie(String name, String value, int expiry, HttpServletResponse response, boolean httpOnly, boolean secure) {
		Cookie cookie = new Cookie(setEncode(name), value);
		cookie.setMaxAge(expiry);
		cookie.setPath("/");
		cookie.setSecure(secure);
		cookie.setHttpOnly(httpOnly);
		setCookie(cookie, response);
	}

	/**
	 * 返回cookie给客户端
	 *
	 * @param cookie
	 * @param response
	 */
	public static void setCookie(Cookie cookie, HttpServletResponse response) {
		response.addCookie(cookie);
	}


	public static String setEncode(String str) {
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {

		}
		return str;
	}

	public static final class FxtCookieKey{
		public static final  String COMPANY_UUID="companyUuid";
		public static final  String LOGIN_METHOD="loginMethod";
		public static final  String UID="uid";
	}
}
